const GroupMessage = require('../../model/groupmessage')

exports.send = async (obj, res) => {
    try {
       var doc = await GroupMessage.create(obj)
     var data = {user:doc.userId,types:doc.types,message:doc.message,tip:doc._id,time:doc.time}

    }
    catch (error) {
        return res.send({
          status:400
        })
    }
    res.send({
      status:200,data
    })
}


exports.getgmessage = async (gid,pagesize,page,res)=>{
  try {
    var total = await GroupMessage.find({groupId:gid}).count()
    var pagecount = Math.ceil(total/pagesize)
    if(page>pagecount){
      return res.send({
        status:201
      })
    }
    var pass =  (page-1)*pagesize
   var doc  = await GroupMessage.find({groupId:gid}).populate('userId').sort({time:-1}).limit(pagesize).skip(pass)
   var data = []
  doc.forEach(item=>{
    data.push({
      user:item.userId._id,
      tip:item._id,
      img:item.userId.avatar,
      types:item.types,
      message:item.message,
      time:item.time
    })
  })

  } catch (error) {
    console.log(error);
    return res.send({
      status:400
    })
  }
  res.send({
    status:200,
    data
  })
}


exports.getnews = async (gid,res)=>{
  try {
     var doc =  await GroupMessage.findOne({groupId:gid}).sort({time:-1}).limit(1)
     var news =''
     var time =''
     if(doc){
       if(doc.types ==0){
         news =doc.message
       }
       if(doc.types ==1){
         news ='[图片]'
       }
       if(doc.types ==2){
         news ='[音频]'
       }
       if(doc.types ==3){
         news ='[定位]'
       }
       time = doc.time
     }
  } catch (error) {
    return res.send({
      status:400
    })
  }
 res.send({
   status:200,
   news,time
 })
}